package com.atguigu.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter的子类
 * HttpObject 客户端和服务器相互通信的数据被封装成HttpObject
 */
public class TestServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        // 判断 msg是不是HttpRequest请求
        if (msg instanceof HttpRequest) {

            System.out.println("ctx 类型：" + ctx.getClass());
            System.out.println("获取channel：" + ctx.channel() + " , pipeLine: " + ctx.pipeline() + " , 通过pipeLine获取channel： " + ctx.pipeline().channel() );
            System.out.println("当前ctx的handler： ：" + ctx.handler() );

            System.out.println("pipeline hashcode:" + ctx.pipeline().hashCode() + " , TestServerHandler hashcode: " + this.hashCode());
            System.out.println("mgs 类型：" + msg.getClass());
            System.out.println("客户端地址：" + ctx.channel().remoteAddress());

            HttpRequest httpRequest = (HttpRequest) msg;
            String stringUri = httpRequest.uri();
            URI uri = new URI(stringUri);
            if ("/favicon.ico".equals(uri.getPath())) {
                System.out.println("请求了favicon.ico，不做处理");
                return;
            }

            // 回复信息给浏览器[http协议]
            ByteBuf content = Unpooled.copiedBuffer("Hello，我是服务器", CharsetUtil.UTF_8);

            // 构造http响应，即HttpResponse
            DefaultHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);

            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=utf-8");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

            // 将构建好的response返回
            ctx.writeAndFlush(response);
        }
    }
}
